var name_pass = false;
var email_pass = false;
var password_pass = false;
var bname_pass = false;


function check_uernamer(input){
	var uname = input.value;
	if(uname!=""&&uname!=null){
		$("#uname-hint").load("check_name/"+uname,
				function (responseText, textStatus, XMLHttpRequest){
				if(responseText == 'valid'){
						$("#uname-hint").html("valid");
						setControlState("#uname-cg",true);
						name_pass = true;
					}else{
						$("#uname-hint").html("this username is invalid");
						setControlState("#uname-cg",false);
						name_pass = false;
					}
				checkAll();
		});
	}
	else{
		$("#uname-hint").html("please input your name");
		setControlState("#uname-cg",false);
		name_pass = false;
	}
	checkAll();
}

function check_email(input){
	var email = input.value;
	if(valid_email(email)){
		$("#email-hint").load("check_email/"+email,
				function(responseText, textStatus, XMLHttpRequest){
					if(responseText == 'valid'){
						this.innerText = "valid";
						setControlState("#email-cg",true);
						email_pass = true;
					}else{
						this.innerText = "this email has been registered";
						setControlState("#email-cg",false);
						email_pass = false;
					}
					checkAll();
		});
	}else{
		$("#email-hint").html("incorrect email address");
		setControlState("#email-cg",false);
		email_pass = false;
	}
	checkAll();
}

function check_psw(psw){
	var password = psw.value; 
	if(password!=""&&password!=null){
		setControlState("#psw-cg",true);
		password_pass = true;
	}else{
		setControlState("#psw-cg",false);
		password_pass = false;
	}
	checkAll();
}
	
function check_bname(bname){
	var blogname = bname.value; 
	if(blogname!=""&&blogname!=null){
		setControlState("#bname-cg",true);
		bname_pass = true;
	}else{
		setControlState("#bname-cg",false);
		bname_pass  = false;
	}
	checkAll();
}

function checkAll(){
	if(name_pass&&email_pass&&password_pass&&bname_pass){
		setBtnState(true);
	}else{
		setBtnState(false);
	}
	
}

function setBtnState(state){
	if(state){
		$("#btn_sbmt").removeClass("disabled");
		$("#btn_sbmt").unbind("click");
		$("#btn_sbmt").click(login);

	}else{
		$("#btn_sbmt").addClass("disabled");
		$("#btn_sbmt").unbind("click");
	}
}

function login(){
	var uname = $("#username")[0].value;
	var psw = $("#password")[0].value;
	var email = $("#email")[0].value;
	var bname = $("#blogname")[0].value;
	
	$.post("register/new",{
			username:uname,
			password:psw,
			email:email,
			blogname:bname
		},
			function(data, textStatus, jqXHR){
				if(data>0){
					window.location.href = base_url;
				}else{
					$('#modal-fail').modal({
					    backdrop:true,
					    keyboard:true,
					    show:true
					});
				}
		}
	);
}